<template>
  <div class="container">
    <el-drawer
      custom-class="wxkj-drawer"
      title="验证你的手机号"
      :visible.sync="drawerShow"
      size="500"
    >
      <div class="drawer-content">
        <el-form ref="form" :model="form" label-width="100px" :rules="rules">
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="验证码：" prop="verifyCode">
            <el-input v-model="form.verifyCode" placeholder="请输入内容">
              <el-button slot="append" :disabled="disabledFlag" @click.native="getCode('form')">{{ codeName }}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item class="fr">
            <el-button @click.native="drawerShow = false">取消</el-button>
            <el-button type="primary" @click.native="bind('form')">绑定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getSmsCode, getSmsCodeToken } from '@/api/user'
import { modifyPhone } from '@/api/settings'
import store from '@/store'
export default {
  components: {},
  props: {
    phone: {
      type: String,
      default: ''
    }
  },
  data() {
    var mobileValidate = (rule, value, callback) => {
      if (!(/^1\d{10}$/.test(value))) {
      	callback(new Error('请准确填写手机号'))
      }
      callback()
    }
    return {
      drawerTitle: '',
      drawerShow: false,
      form: {
        mobile: '',
        verifyCode: ''
      },
      codeName: '获取验证码',
      time: 60,
      rules: {
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: mobileValidate, trigger: 'blur' }
        ],
        verifyCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      disabledFlag: false
    }
  },
  watch: {
    drawerShow(bl) {
      console.log(bl)
      if (!bl) {
        this.$refs.form.resetFields()
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 销毁
  destroyed() {},
  // 方法
  methods: {
    show(title) {
      this.drawerTitle = title
      this.drawerShow = true
    },
    getCode(form) {
      if (this.form.mobile === this.phone) {
        this.$message.error('与原账户一致，请检查')
        return false
      }
      this.$refs[form].validateField('mobile', (valid) => {
        if (!valid) {
          getSmsCodeToken({
            mobile: this.form.mobile
          }).then((res) => {
            if (res.code === 200) {
              const token = res.result.token
              const sign = this.$md5(
                token +
                  this.form.mobile +
                  'EmxJk0VFBgtPfCU5XtZxiVk6rkIGBLwY'
              )
              const that = this
              that.disabledFlag = true
              const interval = setInterval(function() {
                that.codeName = '已发送' + that.time + 's'
                --that.time
                if (that.time < 0) {
                  that.codeName = '重新发送'
                  that.time = 60
                  that.disabledFlag = false
                  clearInterval(interval)
                }
              }, 1000)
              getSmsCode({
                token: token,
                mobile: this.form.mobile,
                sign: sign
              }).then((res) => {
                if (res.code === 200) {
                  this.$message.success('验证码发送成功')
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    bind(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          modifyPhone({ mobile: this.form.mobile, verifyCode: this.form.verifyCode }).then(response => {
            this.$message.success('修改成功')
            this.drawerShow = false
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
            // this.$emit('updatePhone', this.form.mobile)
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
